import re

from rest_framework import serializers
from django.contrib.auth.models import Permission, Group
from django.contrib.contenttypes.models import ContentType

# ================权限数据管理===================
from users.models import User


class PermissionSerializer(serializers.ModelSerializer):
    """权限序列化器类"""

    class Meta:
        model = Permission
        fields = '__all__'


class ContentTypeSerializer(serializers.ModelSerializer):
    """权限类型序列化器类"""

    class Meta:
        model = ContentType
        fields = ('id', 'name')


# ================用户组管理===================

class GroupSerializer(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = '__all__'


class PermSimpleSerializer(serializers.ModelSerializer):
    '''权限简单序列器类'''

    class Meta:
        model = Permission
        fields = ('id', 'name')


# ================管理员用户管理===================

class AdminSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'mobile', 'password',
                  'groups', 'user_permissions')
        extra_kwargs = {
            'password': {'write_only': True,
                         'required': False,
                         'allow_blank': True
                         }
        }

    def validate_mobile(self, value):
        '''验证手机号是否有误'''
        if not re.match(r'1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号码格式有误')
        return value

    # 没有重置密码
    # 没有添加管理员标记
    # 没有给密码加密保存
    def create(self, validated_data):
        '''保存新增管理员用户的数据'''
        # 添加管理员标记
        validated_data['is_staff'] = True
        # 保存新管理员的其他数据(除password)
        user = super().create(validated_data)

        # 判断是否需要设置默认密码,以及密码加密
        password = validated_data.get('password')
        if not password:
            password = '123456abc'
        # 密码加密
        user.set_password(password)
        user.save()

        return user

    # update不能直接使用:理由密码有误
    def update(self, instance, validated_data):
        password = validated_data.pop('password', None)

        # 修改管理员其他数据,(除 password)
        super().update(instance, validated_data)
        # 判断密码是否需要修改
        if password:
            # 不是None,修改密码
            instance.set_password(password)
            instance.save()

        return instance


class GroupSimpleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = ('id', 'name')
